import axios from 'axios'
import { Message } from 'element-ui'
import Store from '@/store'
import Router from '@/router'
const _axios = axios.create({
  baseURL: process.env.VUE_APP_BASE_API
})

// 请求拦截
_axios.interceptors.request.use(
  (config) => {
    if (Store.state.user.token) {
      config.headers.Authorization = `Bearer ${Store.state.user.token}`
    }
    return config
  },
  (error) => {
    //   new Promise((resolve, reject) => {
    //     reject('错误')
    //   })
    //   等效于
    //   Promise.reject('错误')

    return Promise.reject(error)
  }
)
// 失败的拦截
_axios.interceptors.response.use(
  (res) => {
    if (res.data.success) {
      return res.data
    } else {
      Message.error(res.data.message)
      return Promise.reject(res.data.message)
    }
  },
  (error) => {
    if (error.response && error.response.status === 401) {
      Store.commit('user/logout')
      Message.error(error.response.data.message)
      Router.push('/login?redirect=' + window.location.href.split('#')[1])
    }
    return Promise.reject(error)
  }
)
export default _axios
